package dth.dao;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;



import dth.entity.Dealer;
import dth.entity.Distributor;
import dth.entity.Package;

public class DistributorDAO {
	private SessionFactory sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
	private Session session=sessionFactory.openSession();
	public java.util.List<Distributor> getListDistributor()
	{
		session.beginTransaction();
		String queryString="select * from distributor";
		Query query=session.createSQLQuery(queryString).addEntity(Distributor.class);
		return query.list();
	}
	
	public int insert(Distributor distributor)
	{
		Transaction tx=session.beginTransaction();
		String queryString="INSERT into distributor VALUES(0,:name,:date_insert)";
		System.out.println("-----INSERT into distributor VALUES(0,"+distributor.getDistributorName()+","+distributor.getDateInsert());
		Query query=session.createSQLQuery(queryString);
		query.setParameter("name",distributor.getDistributorName());
		query.setParameter("date_insert",distributor.getDateInsert());
		
		int count=query.executeUpdate();
		tx.commit();
		return count;
	}
	public int update(Distributor distributor)
	{
		Transaction tx=session.beginTransaction();
		String queryString="update distributor set distributor_name=:name,date_insert=:date_insert  where distributor_id=:id";
		Query query=session.createSQLQuery(queryString);
		query.setParameter("id",distributor.getDistributorId());
		query.setParameter("name",distributor.getDistributorName());
		query.setParameter("date_insert",distributor.getDateInsert());
		
		int count=query.executeUpdate();
		tx.commit();
		return count;
	}
	public int delete(int id)
	{
		Transaction tx=session.beginTransaction();
		String queryString="delete from distributor where distributor_id= :id";
		Query query=session.createSQLQuery(queryString).setParameter("id", id);
		int count=query.executeUpdate();
		tx.commit();
		return count;
	}
	public List<Distributor> getDistributorByID(int distributorId){
		String queryString="select * from distributor where distributor_id=:id";
		Query query=session.createSQLQuery(queryString).addEntity(Distributor.class);
		query.setParameter("id",distributorId);
		List<Distributor> distributors=query.list();
		return distributors;
	}
}